package com.pansoft.kline.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Html;
import android.text.Spannable;
import android.text.Spanned;
import android.view.View;
import android.widget.TextView;

import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.recycleviewhelper.CommonAdapter;
import com.efounder.recycleviewhelper.base.ViewHolder;
import com.google.gson.Gson;
import com.pansoft.kline.base.KlineBaseFragment;
import com.pansoft.kline.greendao.DaoSessionUtil;
import com.pansoft.kline.model.ConfigCoinBean;
import com.pansoft.kline.model.ConfigMarketBean;
import com.pansoft.kline.model.ConfigSiteBean;
import com.pansoft.kline.model.IntroDataBean;
import com.pansoft.kline.util.BtcKanNumberFormatUtil;
import com.pansoft.kline.util.KLineUtil;
import com.pansoft.kline.util.MarketNumberUtils;
import com.pansoft.kline.widget.NoUnderlineSpan;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.util.TCMathUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.pansoft.openplanet.constant.MarketConstant.MARKET_DETAIL_INTRO_URL;

/**
 * @author : zzj
 * @e-mail : zhangzhijun@pansoft.com
 * @date : 2018/11/10 13:51
 * @desc :  简况fragment
 * @version: 1.0
 */
public class DealRealBriefingFragment extends KlineBaseFragment {

    private TextView tvAbout;
    private TextView tvCnName;
    private TextView tvEnName;
    private TextView tvType;
    private TextView tvFaxingTime;
    private TextView tvCirculateAmount;
    private TextView tvFaxingAmount;
    private TextView tvRanking;
    private TextView tvShgizhi;
    private TextView tvQuanqiuZhanbi;
    private TextView tvLiutonglv;
    private TextView tvHuanshoulv;
    private TextView tvIcoChengben;
    private TextView tvMujiZijin;
    private TextView tvTokenAllot;
    private TextView tvWhitePaper;
    private TextView tvSiteCount;
    private TextView tvGuangwang;
    private RecyclerView recycleview;

    private String marketId;
    private ConfigMarketBean marketBean;
    private ConfigCoinBean coinBean;
    private ConfigSiteBean siteBean;

    private IntroDataBean introDataBean;
    private TextView tvName;
    private BriefingSiteAdater mAdapter;
    private List<IntroDataBean.DataBean.RecommendSiteBean> listData;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    public static DealRealBriefingFragment newInstance(String marketId) {

        Bundle args = new Bundle();
        args.putString("marketId", marketId);
        DealRealBriefingFragment fragment = new DealRealBriefingFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_deal_real_briefing;
    }

    @Override
    protected void initArgs(Bundle bundle) {
        super.initArgs(bundle);
        marketId = bundle.getString("marketId");
        marketBean = DaoSessionUtil.getInstance().getConfigMarketBeanDao().load(marketId);
        coinBean = DaoSessionUtil.getInstance().getConfigCoinBeanDao().load(marketBean.getCoin());
        siteBean = DaoSessionUtil.getInstance().getConfigSiteBeanDao().load(marketBean.getSite());
    }

    @Override
    protected void initWidget(View root) {

        tvAbout = (TextView) root.findViewById(R.id.tv_about);
        tvCnName = (TextView) root.findViewById(R.id.tv_cn_name);
        tvEnName = (TextView) root.findViewById(R.id.tv_en_name);
        tvType = (TextView) root.findViewById(R.id.tv_type);
        tvFaxingTime = (TextView) root.findViewById(R.id.tv_faxing_time);
        tvCirculateAmount = (TextView) root.findViewById(R.id.tv_circulate_amount);
        tvFaxingAmount = (TextView) root.findViewById(R.id.tv_faxing_amount);
        tvRanking = (TextView) root.findViewById(R.id.tv_ranking);
        tvShgizhi = (TextView) root.findViewById(R.id.tv_shgizhi);
        tvQuanqiuZhanbi = (TextView) root.findViewById(R.id.tv_quanqiu_zhanbi);
        tvLiutonglv = (TextView) root.findViewById(R.id.tv_liutonglv);
        tvHuanshoulv = (TextView) root.findViewById(R.id.tv_huanshoulv);
        tvIcoChengben = (TextView) root.findViewById(R.id.tv_ico_chengben);
        tvMujiZijin = (TextView) root.findViewById(R.id.tv_muji_zijin);
        tvTokenAllot = (TextView) root.findViewById(R.id.tv_token_allot);
        tvWhitePaper = (TextView) root.findViewById(R.id.tv_white_paper);
        tvSiteCount = (TextView) root.findViewById(R.id.tv_site_count);
        tvGuangwang = (TextView) root.findViewById(R.id.tv_guangwang);
        tvName = (TextView) root.findViewById(R.id.tv_name);
        recycleview = (RecyclerView) root.findViewById(R.id.recycleview);
        super.initWidget(root);
    }


    @Override
    protected void initListener() {
        super.initListener();
    }

    @Override
    protected void initAdapter() {
        super.initAdapter();
        recycleview.setNestedScrollingEnabled(false);
        recycleview.setLayoutManager(new LinearLayoutManager(getActivity()));

        listData = new ArrayList<>();
        mAdapter = new BriefingSiteAdater(getActivity(), R.layout.assets_item_deal_real_briefing, listData);
        recycleview.setAdapter(mAdapter);
    }

    @Override
    protected void initData() {
        super.initData();

        requestData();
    }


    /**
     * 简介的数据
     */
    public void requestData() {
        HashMap<String, String> hashMap = new HashMap<>();
        //>https://x.szsing.com:443/v2/quote/price/m_coin_detail/KAN
        JFCommonRequestManager.getInstance(getActivity()).requestGetByAsyn(TAG, MARKET_DETAIL_INTRO_URL + "/" + coinBean.getCoinKey(),
                hashMap, new JFCommonRequestManager.ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(String result) {
                        try {
                            introDataBean = new Gson().fromJson(result, IntroDataBean.class);
                            refreshPage();
                        } catch (Exception e) {
                            e.printStackTrace();
                            // ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);
                        }
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
                        //ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail_abnormal);
                    }
                });

    }

    /**
     * 刷新界面数据
     */
    public void refreshPage() {
        if (introDataBean == null) {
            return;
        }
        if (introDataBean.getCode() != 0) {
            return;
        }

        IntroDataBean.DataBean.CoinBean coinBean = introDataBean.getData().getCoin();
        tvName.setText(coinBean.getCoin() + "(" + coinBean.getEn_title() + "、" + coinBean.getHans_title() + ")");
        tvAbout.setText(Html.fromHtml(coinBean.getIntroduce()));
        tvCnName.setText(coinBean.getHans_title());
        tvEnName.setText(coinBean.getEn_title());
        tvType.setText(replaceText(coinBean.getType()));
        tvFaxingTime.setText(coinBean.getIco_time());
        //流通总量
        tvCirculateAmount.setText(MarketNumberUtils.amountConversion(Double.valueOf(coinBean.getAvailable_supply())));
        tvFaxingAmount.setText(MarketNumberUtils.amountConversion(Double.valueOf(coinBean.getTotal_supply())));
        tvRanking.setText(coinBean.getRank());

        double cap = MarketNumberUtils.getRealPrice(siteBean.getUniqueKey(), marketBean.getCurrency(), wantCurrency, Double.valueOf(coinBean.getCap()));
        tvShgizhi.setText(KLineUtil.getCurrencySymbol(wantCurrency) + MarketNumberUtils.amountConversion(cap));
        tvQuanqiuZhanbi.setText(BtcKanNumberFormatUtil.getPercent(Double.valueOf(coinBean.getProportion())));

        //计算百分比
        String liutongPercent = BtcKanNumberFormatUtil.getPercent(TCMathUtil.div(Double.valueOf(coinBean.getAvailable_supply()), Double.valueOf(coinBean.getTotal_supply()), 4));
        tvLiutonglv.setText(liutongPercent);

        //换手率 volume/ available_supply
        String huanshouPercent = BtcKanNumberFormatUtil.getPercent(TCMathUtil.div(Double.valueOf(coinBean.getVolume()), Double.valueOf(coinBean.getAvailable_supply()), 4));
        tvHuanshoulv.setText(huanshouPercent);

        tvIcoChengben.setText(coinBean.getIco_cost());
        tvMujiZijin.setText(coinBean.getIco_amount());
        tvTokenAllot.setText(coinBean.getIco_dispatch());
        tvWhitePaper.setText(coinBean.getWhite_paper());
        tvSiteCount.setText(coinBean.getExchange_sites());
        tvGuangwang.setText(coinBean.getWeb_site());
        setNoUnderLine(tvGuangwang);
        setNoUnderLine(tvWhitePaper);
        listData.clear();
        listData.addAll(introDataBean.getData().getRecommend_site());
        mAdapter.notifyDataSetChanged();

    }

    private String replaceText(String text) {
        if (text == null || "".equals(text)) {
            return "--";
        }
        return text;
    }

    private void setNoUnderLine(TextView textView) {

        NoUnderlineSpan mNoUnderlineSpan = new NoUnderlineSpan();
        if (textView.getText() instanceof Spannable) {
            Spannable s = (Spannable) textView.getText();
            s.setSpan(mNoUnderlineSpan, 0, s.length(), Spanned.SPAN_MARK_MARK);

        }
    }

    public static class BriefingSiteAdater extends CommonAdapter<IntroDataBean.DataBean.RecommendSiteBean> {
        public BriefingSiteAdater(Context context, int layoutId, List<IntroDataBean.DataBean.RecommendSiteBean> datas) {
            super(context, layoutId, datas);
        }

        @Override
        protected void convert(ViewHolder holder, final IntroDataBean.DataBean.RecommendSiteBean recommendSiteBean, int position) {

            TextView tvMarketName = holder.getView(R.id.tv_market_name);
            TextView tvCoinCurrency = holder.getView(R.id.tv_coin_currency);
            TextView tvVol = holder.getView(R.id.tv_vol);
            TextView tvLocale = holder.getView(R.id.tv_locale);
            TextView tvWeb = holder.getView(R.id.tv_web);
            tvMarketName.setText(recommendSiteBean.getHans_title());
            tvCoinCurrency.setText(recommendSiteBean.getCoin() + "/" + recommendSiteBean.getCurrency());

            tvWeb.setText(recommendSiteBean.getUrl());
            tvLocale.setText(recommendSiteBean.getHans_locale());
            setNoUnderLine(tvWeb);

            String vol = mContext.getResources().getString(R.string.chart_kline_detail_briefing_trading_volume_24H)
                    +" " + TCMathUtil.retainAsignDecimals(Double.valueOf(recommendSiteBean.getVol()), 0);
            tvVol.setText(vol);
            holder.getConvertView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        Intent intent = new Intent();
                        intent.setAction("android.intent.action.VIEW");
                        Uri content_url = Uri.parse(recommendSiteBean.getUrl());
                        intent.setData(content_url);
                        mContext.startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

        }

        private void setNoUnderLine(TextView textView) {

            NoUnderlineSpan mNoUnderlineSpan = new NoUnderlineSpan();
            if (textView.getText() instanceof Spannable) {
                Spannable s = (Spannable) textView.getText();
                s.setSpan(mNoUnderlineSpan, 0, s.length(), Spanned.SPAN_MARK_MARK);

            }
        }
    }
}
